package demo5;

import demo4.IsEmptyException;
import demo4.IsFullException;

//使用标记为实现循环队列
public class MyQueue {
    public int[] elem;
    public boolean flag;  //标记位
    public int rear;
    public int front;


    //无参构造
    public MyQueue() {
        this.elem = new int[3];
    }

    //入队
    public void offer(int val) {
        if (isFull()) {
            throw new IsFullException("队列满!");
        }
        this.elem[rear] = val;
        this.rear = (this.rear + 1) % this.elem.length;
        this.flag = true;
    }
    //出队
    public int poll() {
        if (isEmpty()) {
            throw new IsEmptyException("队列为空");
        }
        int val = this.elem[front];
        this.front = (this.front + 1) % this.elem.length;
        this.flag = false;
        return val;
    }

    //获得对顶元素
    public int peek() {
        if (isEmpty()) {
            throw new IsEmptyException("队列为空");
        }
        return this.elem[front];
    }

    //获得队列的有效数字的大小
    public int size() {
        if (isEmpty()) {
            return 0;
        }
        if (isFull()) {
            return this.elem.length;
        }
        int curFront = this.front;
        int count = 0;
        while (curFront != this.rear) {
            curFront = (curFront + 1) % this.elem.length;
            count++;
        }
        return count;
    }
    //判断队列是不是空
    public boolean isEmpty() {
        return this.rear == this.front && !flag;
    }


    //判断队列是不是满
    public boolean isFull() {
        if (this.flag && this.rear == this.front) {
            return true;
        }
        return false;
    }


}
